package io.renren.modules.app.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.modules.app.dao.WechatTokenDao;
import io.renren.modules.app.entity.WechatToken;
import io.renren.modules.app.service.WechatTokenService;
import io.renren.modules.app.wx.WeChatUtil;
import io.renren.modules.app.wx.WxAppIdEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("WechatTokenService")
public class WechatTokenServiceImpl extends ServiceImpl<WechatTokenDao, WechatToken> implements WechatTokenService {

    @Autowired
    private WechatTokenDao wechatTokenDao;


    @Override
    public String getToken(){
        WechatToken wechatToken = wechatTokenDao.selectOne(new LambdaQueryWrapper<WechatToken>()
                .eq(WechatToken::getAppId, WxAppIdEnum.TAI_HUA_MP.getAppId())
                .last("limit 1")
        );
        if (wechatToken == null) {
            throw new RRException("app_id 不存在");
        }
        Date lastUpdatedAt = wechatToken.getLastUpdatedAt();
        if (DateUtil.offsetHour(lastUpdatedAt,1).getTime()>System.currentTimeMillis()) {
            return wechatToken.getToken();
        }else {
            try {
                String accessToken = WeChatUtil.getAccessToken();
                wechatToken.setToken(accessToken);
                wechatToken.setLastUpdatedAt(new Date());
                wechatTokenDao.updateById(wechatToken);
                return wechatToken.getToken();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
